const mysql = require('mysql');
const { SDK } = require('tencentcloud-serverless-nodejs');
const mysqlConfig = require('./mysqlconfig.js');
const tencentConfig = require('./tencentconfig.js');

function wrapDeletePromise(connection) {
  return new Promise((res, rej) => {
    connection.query('DELETE FROM convertible_bond_hook WHERE 1', function(error, results, fields) {
      if (error) {
        rej(error)
      }
      res(results)
    })
  })
}
function wrapInsertPromise(connection, values) {
  return new Promise((res, rej) => {
    connection.query('INSERT INTO convertible_bond_hook(name, code, creatline, addline, heavyline, research_degree, safe_degree, rating, comment, qualification) VALUES ?', [values], function(error, results, fields) {
      if (error) {
        rej(error)
      }
      res(results)
    })
  })
}

async function updatePrice() {
  const sdk = new SDK({
    region:'ap-beijing',
    secretId: tencentConfig.secretId,
    secretKey: tencentConfig.secretKey
  });
  return await sdk.invoke({
    functionName: 'ConvertibleUpdateprice',
    qualifier: '$LATEST',
    namespace:'convertible',

  });
}


exports.main_handler = async (event, context, callback) => {
  let res = null;
  let connection = null;
  try {
    const hookfileData = JSON.parse(event.body);
    const values = hookfileData.map(item => [item.name, item.code, item.creatline, item.addline, item.heavyline, item.research_degree, item.safe_degree, item.rating, item.comment, item.qualification]);
    connection = mysql.createConnection({
      ...mysqlConfig,
      charset : 'utf8mb4'
    });
    connection.connect();
    await wrapDeletePromise(connection);
    console.log(values);
    await wrapInsertPromise(connection, values);
    res = await updatePrice();
  } catch (error) {
    console.log('error', error);
    res = error;
  } finally {
    connection && connection.end();
  }
  
  return res;
}

